import React, { useState, useEffect } from 'react';

import { Modal, Row, Col, Button, Select, Radio, Input, InputNumber, DatePicker, Checkbox } from 'antd';

const { RangePicker } = DatePicker;
const { Option } = Select;

import moment from 'moment';


function Calendar(props) {
    let [batchVisible, setBatchModal] = useState(false);
    let [ data, setData ] = useState([]);
    let [ date, setDate ] = useState({ y: moment(props.date[0]).year(), m: moment(props.date[0]).month() + 1 });
    let [option, setOption] = useState({
        dateRange: props.date,
        type: 3,
        checkAll: true,
        week: [1, 2, 3, 4, 5, 6, 0],
        adultPrice: '',
        adultStock: '',
        adultCostPrice: '',
        childrenPrice: '',
        childrenStock: '',
        childrenCostPrice: '',
        diffPrice: ''
    });

    let [ tmpCalendarMap, setTmpCalendarMap] = useState([]);


    let optionChangeHandler = (k, v) => {
        console.log(v)
        option[k] = v;
        if (option.week.length === 7) {
            option['checkAll'] = true;
        }
        setOption({ ...option });
    };
    let changeDateHandler = (k, v) => {
        //back
        let d = `${date.y}-${date.m}`;
        let index = '';
        for (let i = 0; i < tmpCalendarMap.length; i++) {
            if (moment(tmpCalendarMap[i].date).isSame(d, 'month')) {
                index = i;
                tmpCalendarMap[i].list = JSON.parse(JSON.stringify(data));
                break;
            }
        }
        if (index === '') {
            tmpCalendarMap.push({ date: d, list: data });
        }

        date[k] = v;
        setDate({ ...date });

        let backData = tmpCalendarMap.filter(item => moment(`${date.y}-${date.m}`).isSame(item.date, 'month'));
        console.log('tmpCalendarMap', tmpCalendarMap);
        if (backData.length) {
            console.log('back===')
            setData(backData[0].list);
        } else {
            console.log('init===')
            initCalendar();
        }
    };
    let changeHandler = (i, j, k, v) => {
        data[i][j][k] = v.target.value;
        setData([...data]);
    };

    let getCountDays = (date) => {
        let curDate = date.years? new Date(date.years) : new Date();
        /* 获取当前月份 */
        var curMonth = date.month? (date.month - 1) : curDate.getMonth();

        curDate.setMonth(curMonth + 1);

        curDate.setDate(0);
        /* 返回当月的天数 */
        let countDaysNum = curDate.getDate();
        let countDays = [];
        for( let i = 0; i < countDaysNum; i++ ) {
            countDays.push({ day: i + 1 });
        }
        let empty = [];
        let week = moment(moment().format('YYYY-MM')+'-01').weekday();
        if (week < 7 ) {
            for( let i = 1; i < week; i++ ) {
                empty.push({ day: '' });
            }
        }
        countDays = empty.concat(countDays);
        let len = countDays.length;
        for( let i = 0; i < 42 - len; i++ ) {
            countDays.push({ day: '' });
        }
        let arrayDays = [];
        for (let i = 0; i < 6; i++) {
            arrayDays.push(countDays.splice(0, 7));
        }
        //console.log(arrayDays)
        return arrayDays;
    };
    let initCalendar = (isClearRedraw = false) => {
        let days = getCountDays({ years: date.y, month: date.m });
        let startDate = moment(props.date[0]).subtract(1, 'days').endOf('day');
        let endDate = props.date[1].endOf('day');
        let priceList = props.priceList;
        for (let i = 0; i < days.length; i++) {
            for (let j = 0; j < days[i].length; j++) {
                let current = days[i][j].day? `${date.y}-${date.m}-${days[i][j].day}` : false;
                let tmp = {
                    adult_cost_price: "",
                    adult_sale_price: "",
                    adult_sale_stock: "",
                    children_cost_price: "",
                    children_sale_price: "",
                    children_number: "",
                    room_diff_price: ""
                };
                if (priceList.length > 0 && !isClearRedraw) {
                    for (let f = 0; f < priceList.length; f++) {
                        if (current && moment(priceList[f].date).isSame(current, 'day')) {
                            Object.assign(tmp, { ...priceList[f] });
                            break;
                        }
                    }
                }
                Object.assign(days[i][j], {
                    ...tmp,
                    disabled: current && !(moment(current).isBetween(startDate, endDate))
                });
            }
        }
        setData(days);
    };

    useEffect(() => {
        if (props.date.length && props.visible) {
            setOption({ ...option, dateRange: props.date });
            date = { y: moment(props.date[0]).year(), m: moment(props.date[0]).month() + 1 };
            setDate(date);
            initCalendar();
            console.log('init');
        }
    }, [props.date, props.visible]);
    console.log('load')

    let handleOk = () => {
        props.setVisible(false);
        emitData();
    };
    let emitData = () => {
        let tmp = [];
        let current = `${date.y}-${date.m}`;
        for (let i = 0; i < data.length; i++) {
            if (isBetween(`${current}-${data[i].day}`)) {
                let {
                    adult_cost_price,
                    adult_sale_price,
                    adult_sale_stock,
                    children_cost_price,
                    children_sale_price,
                    children_number,
                    room_diff_price } = data[i];
                tmp.push({
                    adult_cost_price,
                    adult_sale_price,
                    adult_sale_stock,
                    children_cost_price,
                    children_sale_price,
                    children_number,
                    room_diff_price,
                    date: `${current}-${data[i].day}`,
                });
            }
        }

        for (let i = 0; i < tmpCalendarMap.length; i++) {
            if (!(moment(current).isSame(tmpCalendarMap[i].date))) {
                let list = tmpCalendarMap[i].list;
                list.forEach(item => {
                    if (isBetween(`${current}-${item.day}`)) {
                        let {
                            adult_cost_price,
                            adult_sale_price,
                            adult_sale_stock,
                            children_cost_price,
                            children_sale_price,
                            children_number,
                            room_diff_price } = item;
                        tmp.push({
                            adult_cost_price,
                            adult_sale_price,
                            adult_sale_stock,
                            children_cost_price,
                            children_sale_price,
                            children_number,
                            room_diff_price,
                            date: `${current}-${item.day}`,
                        });
                    }
                });
            }
        }

        props.emitChange(tmp);
    };
    let isBetween = (current) => (moment(current).isBetween(moment(props.date[0]).subtract(1, 'days').endOf('day'), props.date[1].endOf('day')));
    let handleCancel = () => {
        props.setVisible(false);
        revertCalendar();
        setBatchModal(false);
    };
    let revertCalendar = () => {
        tmpCalendarMap = [];
        date = { y: moment(props.date[0]).year(), m: moment(props.date[0]).month() + 1 };
        setDate({ ...date });
        initCalendar();
    };

    let confirmBatchSet = () => {
        let current = `${date.y}-${date.m}`;
        for (let i = 0; i < data.length; i++) {
            let item = data[i];
            for (let j = 0;  j < item.length; j++) {
                if (item[j].day) {
                    batchSetHandler(`${current}-${item[j].day}`, item[j]);
                }
            }
        }
        for (let i = 0; i < tmpCalendarMap.length; i++) {
            if (!(moment(current).isSame(tmpCalendarMap[i].date, 'month'))) {
                let list = tmpCalendarMap[i].list;
                for (let i = 0; i < list.length; i++) {
                    let item = list[i];
                    for (let j = 0;  j < item.length; j++) {
                        if (item[j].day) {
                            batchSetHandler(`${current}-${item[j].day}`, item[j]);
                        }
                    }
                }
            }
        }

        setData([ ...data ]);
        setBatchModal(false);
    };
    let batchSetHandler = (current, item) => {
        let {
            dateRange,
            type,
            week,
            adultPrice,
            adultStock,
            adultCostPrice,
            childrenPrice,
            childrenStock,
            childrenCostPrice,
            diffPrice } = option;
        if (!(moment(current).isBetween(moment(dateRange[0]).subtract(1, 'days').endOf('day'), dateRange[1].endOf('day')))) {
            return;
        }
        switch(type) {
            case 1:
                if (parseInt(item.day) % 2 === 0) {
                    return;
                }
                break;
            case 2:
                if (parseInt(item.day) % 2 !== 0) {
                    return;
                }
                break;
            case 3:
                if (week.indexOf(moment(current).weekday()) < 0) {
                    return;
                }
                break;
        }
        Object.assign(item, {
            adult_cost_price: adultCostPrice,
            adult_sale_price: adultPrice,
            adult_sale_stock: adultStock,
            children_cost_price: childrenCostPrice,
            children_sale_price: childrenPrice,
            children_number: childrenStock,
            room_diff_price: diffPrice
        });
    };

    let onCheckAllChange = e => {
        setOption({
            ...option,
            week: e.target.checked ? [1, 2, 3, 4, 5, 6, 0] : [],
            checkAll: e.target.checked,
        });
    };

    let clearByItem = item => {
        Object.assign(item, {
            adult_cost_price: '',
            adult_sale_price: '',
            adult_sale_stock: '',
            children_cost_price: '',
            children_sale_price: '',
            children_number: '',
            room_diff_price: ''
        });
        setData([ ...data ]);
    };

    let clearAll = () => {
        tmpCalendarMap = [];
        initCalendar(true);
    };

    let Footer = (
        <Row>
            <Col align={'left'} span={12}><Button onClick={() => setBatchModal(true)}>批量设置</Button><Button danger onClick={clearAll}>清空全部</Button></Col>
            <Col span={12}><Button type="primary" onClick={handleOk}>保存</Button><Button onClick={handleCancel}>取消</Button></Col>
        </Row>
    );
    let handleTypeChange = (v) => {

    };
    return (
        <Modal
            title="价格日历"
            visible={props.visible}
            maskClosable={false}
            width={'85%'}
            footer={Footer}
            onCancel={handleCancel}
        >
            <Row>
                <Col span={12}></Col>
                <Col span={12} align="right">
                    <Select
                        className="mr10-sel"
                        size="small"
                        value={date.y}
                        onChange={(v) => { changeDateHandler('y', v) }}
                    >
                        <Option value={2020}>2020</Option>
                        <Option value={2021}>2020</Option>
                        <Option value={2022}>2020</Option>
                        <Option value={2023}>2020</Option>
                        <Option value={2024}>2020</Option>
                    </Select>
                    <Select
                        className="mr10-sel"
                        size="small"
                        value={date.m}
                        onChange={(v) => { changeDateHandler('m', v) }}
                    >
                        <Option value={1}>1月</Option>
                        <Option value={2}>2月</Option>
                        <Option value={3}>3月</Option>
                        <Option value={4}>4月</Option>
                        <Option value={5}>5月</Option>
                    </Select>
                    <Radio.Group size="small" value={'m'} onChange={handleTypeChange}>
                        <Radio.Button value="m">月</Radio.Button>
                        <Radio.Button value="y">年</Radio.Button>
                    </Radio.Group>
                </Col>
            </Row>
            <Row className="day-box">
                <Col span={24}>
                    <ul className="week-title">
                        <li>周一</li>
                        <li>周二</li>
                        <li>周三</li>
                        <li>周四</li>
                        <li>周五</li>
                        <li>周六</li>
                        <li>周日</li>
                    </ul>
                    {
                        data.map((days, index) => (
                            <ul className="days" key={index}>
                                {
                                    days.map((item, j) => (
                                        !!item.day?
                                        <li className={[item.disabled? 'disabled-day' : 'calendar-cell'].join(' ')} key={j}>
                                            <div className="calendar-cell-value">
                                                {
                                                    item.disabled?
                                                        null : (<Button type="link" size="mini" onClick={() => clearByItem(item)}>清除</Button>)
                                                }
                                                <span style={{marginLeft: '90px'}}>{item.day}</span>
                                            </div>
                                            <div className="calendar-cell-content">
                                                <div className="calendar-cell-content-row">
                                                    <div className="number-picker">
                                                        <Input type="number" size="small" addonBefore="￥" placeholder="成人价" disabled={item.disabled} value={item.adult_sale_price} onChange={(v) => changeHandler(index, j, 'adult_sale_price', v)} />
                                                    </div>
                                                    <div className="number-picker">
                                                        <Input type="number" size="small" addonAfter="人" placeholder="名额" disabled={item.disabled} value={item.adult_sale_stock} onChange={(v) => changeHandler(index, j, 'adult_sale_stock', v)}/>
                                                    </div>
                                                </div>
                                                <div className="calendar-cell-content-row">
                                                    <div className="number-picker">
                                                        <Input type="number" size="small" addonBefore="￥" placeholder="儿童价" disabled={item.disabled} value={item.children_sale_price} onChange={(v) => changeHandler(index, j, 'children_sale_price', v)}/>
                                                    </div>
                                                    <div className="number-picker">
                                                        <Input type="number" size="small" addonAfter="人" placeholder="名额" disabled={item.disabled} value={item.children_number} onChange={(v) => changeHandler(index, j, 'children_number', v)}/>
                                                    </div>
                                                </div>
                                                <div className="calendar-cell-content-row">
                                                    <div className="number-picker">
                                                        <Input type="number" size="small" addonBefore="￥" placeholder="成人底价" disabled={item.disabled} value={item.adult_cost_price} onChange={(v) => changeHandler(index, j, 'adult_cost_price', v)}/>
                                                    </div>
                                                    <div className="number-picker">
                                                        <Input type="number" size="small" addonBefore="￥" placeholder="儿童底价" disabled={item.disabled} value={item.children_cost_price} onChange={(v) => changeHandler(index, j, 'children_cost_price', v)}/>
                                                    </div>
                                                </div>
                                                <div className="calendar-cell-content-row">
                                                    <div className="number-picker w100">
                                                        <Input type="number" size="small" addonBefore="￥" placeholder="单房差" disabled={item.disabled} value={item.room_diff_price} onChange={(v) => changeHandler(index, j, 'room_diff_price', v)}/>
                                                    </div>
                                                </div>
                                            </div>
                                        </li> : <li className="disabled-day" key={j}></li>
                                    ))
                                }
                            </ul>
                        ))
                    }
                </Col>
            </Row>
            {
                batchVisible? (
                    <div className="batch-setting-box">
                        <Row className="mb15">
                            <Col span={4}>时间段</Col>
                            <Col span={12}>
                                <RangePicker
                                    value={option.dateRange}
                                    onChange={(v) => optionChangeHandler('dateRange', v)}
                                    disabledDate={(current) => (current && !(moment(current).isBetween(moment(props.date[0]).subtract(1, 'days').endOf('day'), props.date[1].endOf('day'))))}
                                />
                            </Col>
                        </Row>
                        <Row className="mb15">
                            <Col span={4}>日历类型</Col>
                            <Col span={12}>
                                <Radio.Group size="small" value={option.type} onChange={(v) => optionChangeHandler('type', v.target.value)}>
                                    <Radio value={1}>仅单日</Radio>
                                    <Radio value={2}>仅双日</Radio>
                                    <Radio value={3}>按星期</Radio>
                                </Radio.Group>
                                {
                                    option.type === 3? (
                                        <div>
                                            <Checkbox.Group value={option.week} onChange={(v) => optionChangeHandler('week', v)}>
                                                <Checkbox value={1}>周一</Checkbox>
                                                <Checkbox value={2}>周二</Checkbox>
                                                <Checkbox value={3}>周三</Checkbox>
                                                <Checkbox value={4}>周四</Checkbox>
                                                <Checkbox value={5}>周五</Checkbox>
                                                <Checkbox value={6}>周六</Checkbox>
                                                <Checkbox value={0}>周日</Checkbox>
                                            </Checkbox.Group>
                                            <Checkbox
                                                indeterminate={option.week.length < 7 && option.week.length > 0}
                                                onChange={onCheckAllChange}
                                                checked={option.checkAll}>
                                                全选
                                            </Checkbox>
                                        </div>
                                    ) : null
                                }
                            </Col>
                        </Row>
                        <Row className="mb15">
                            <Col span={4}>价格库存</Col>
                            <Col span={6}>
                                <div className="calendar-cell-content">
                                    <div className="calendar-cell-content-row">
                                        <div className="number-picker">
                                            <Input type="number" addonBefore="￥" placeholder="成人价" value={option.adultPrice} onChange={(v) => optionChangeHandler('adultPrice', v.target.value)} />
                                        </div>
                                        <div className="number-picker">
                                            <Input type="number" addonBefore="库存" placeholder="库存" value={option.adultStock} onChange={(v) => optionChangeHandler('adultStock', v.target.value)}/>
                                        </div>
                                    </div>
                                    <div className="calendar-cell-content-row">
                                        <div className="number-picker">
                                            <Input type="number" addonBefore="￥" placeholder="儿童价" value={option.childrenPrice} onChange={(v) => optionChangeHandler('childrenPrice', v.target.value)}/>
                                        </div>
                                        <div className="number-picker">
                                            <Input type="number" addonBefore="库存" placeholder="库存" value={option.childrenStock} onChange={(v) => optionChangeHandler('childrenStock', v.target.value)}/>
                                        </div>
                                    </div>
                                    <div className="calendar-cell-content-row">
                                        <div className="number-picker">
                                            <Input type="number" addonBefore="￥" placeholder="成人底价" value={option.adultCostPrice} onChange={(v) => optionChangeHandler('adultCostPrice', v.target.value)}/>
                                        </div>
                                        <div className="number-picker">
                                            <Input type="number" addonBefore="￥" placeholder="儿童底价" value={option.childrenCostPrice} onChange={(v) => optionChangeHandler('childrenCostPrice', v.target.value)}/>
                                        </div>
                                    </div>
                                    <div className="calendar-cell-content-row">
                                        <div className="number-picker w100">
                                            <Input type="number" addonBefore="￥" placeholder="单房差" value={option.diffPrice} onChange={(v) => optionChangeHandler('diffPrice', v.target.value)}/>
                                        </div>
                                    </div>
                                </div>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={4}></Col>
                            <Col span={2}>
                                <Button type="primary" onClick={confirmBatchSet}>确认</Button>
                            </Col>
                            <Col span={2}>
                                <Button onClick={() => setBatchModal(false)}>取消</Button>
                            </Col>
                        </Row>
                    </div>
                ) : null
            }
        </Modal>
    )
};

export default React.memo(Calendar);